Ext.ns('AIR2.Import.Resolve');
/***************
 * Import conflict resolver
 *
 * Opens a modal window allowing the resolution of any conflicts on a Source
 * that is being imported.
 *
 * @function AIR2.Import.Resolve
 * @cfg {String} url
 * @cfg {HTMLElement} originEl (optional) origin element to animate from
 *
 */
AIR2.Import.Resolve = function(cfg) {
    // map the non-fact parts of the TankSource
    var map = {
        Source: AIR2.Import.Resolve.Source,
        //SrcAlias: AIR2.Import.Resolve.SrcAlias,
        SrcMailAddress: AIR2.Import.Resolve.SrcMailAddress,
        SrcPhoneNumber: AIR2.Import.Resolve.SrcPhoneNumber,
        SrcEmail: AIR2.Import.Resolve.SrcEmail
        //SrcUri: AIR2.Import.Resolve.SrcUri,
        //SrcOrg: AIR2.Import.Resolve.SrcOrg,
        //SrcAnnotation: AIR2.Import.Resolve.SrcAnnotation,
        //SrcVita: AIR2.Import.Resolve.SrcVita,
        //SrcActivity: AIR2.Import.Resolve.SrcActivity
    };

    // load the tank_source
    var store = new Ext.data.JsonStore({
        url: cfg.url+'.json',
        autoLoad: true,
        listeners: {
            load: function(store, rs) {
                w.setTankSource(rs[0].data);
            }
        }
    });

    // buttons
    var statusFld = new Ext.BoxComponent({
        cls: 'submit-status',
        showSuccess: function(msg) {
            statusFld.update('<div class="air2-icon air2-icon-check">'+msg+'</div>');
            statusFld.show();
        },
        showFailure: function(msg) {
            statusFld.update('<div class="air2-icon air2-icon-error">'+msg+'</div>');
            statusFld.show();
        }
    });
    var submitBtn = new AIR2.UI.Button({
        air2type: 'BLUE',
        air2size: 'MEDIUM',
        text: 'Submit Resolution',
        formBind: true,
        handler: function(btn) {
            // remote waiting message
            btn.remoteWait.alignTo(btn.btnEl, 'l-r', [5,0]);
            btn.remoteWait.show();
            statusFld.hide();
            w.get(0).stopMonitoring();
            btn.disable();

            // fire ajax submit
            var f = w.get(0).getForm();
            f.submit({
                url: cfg.url+'/resolve.json',
                params: {
                    ops: Ext.encode(f.getValues())
                },
                success: function(form, action) {
                    btn.remoteWait.hide();
                    btn.disable();
                    statusFld.showSuccess(action.result.message);

                    // refresh the curr-value panels
                    w.get(0).items.each(function(item) {
                        item.get(0).doAutoLoad();
                        item.get(1).disable();
                    });
                    w.close.defer(1500, w);
                },
                failure: function(form, action) {
                    btn.remoteWait.hide();
                    w.get(0).startMonitoring();
                    if (action.result && action.result.message) {
                        var errs = Ext.decode(action.result.radix.tsrc_errors);
                        var msg = action.result.message;
                        msg += ': '+errs.resolve.length+' unresolved conflicts (';
                        for (var i=0; i<errs.resolve.length; i++) {
                            msg += (i == 0) ? '' : ', ';
                            msg += errs.resolve[i].model;
                        }
                        msg += ')';
                        statusFld.showFailure(msg);
                        Logger("FAILURE", errs);
                    }
                    else {
                        statusFld.showFailure('Server error!');
                    }
                }
            });
        },
        listeners: {
            render: function(btn) {
                btn.remoteWait = btn.el.createChild({cls: 'air2-form-remote-wait'});
            }
        }
    });

    var w = new AIR2.UI.Window({
        title: 'Resolve Conflicts',
        iconCls: 'air2-icon-source',
        cls: 'air2-resolve',
        closeAction: 'close',
        width: 720,
        height: 500,
        items: {
            xtype: 'form',
            unstyled: true,
            autoScroll: true,
            monitorValid: true,
            buttonAlign: 'left',
            buttons: [submitBtn, statusFld],
            items: {
                /* temp loading element */
                xtype: 'box',
                listeners: {
                    render: function(box) {
                        box.ownerCt.el.mask('Loading...');
                    },
                    removed: function(box, owner) {
                        box.ownerCt.el.unmask();
                    }
                }
            }
        },
        setTankSource: function(data) {
            // clear the window
            w.get(0).removeAll(true);
            w.panelMap = {};

            // get the conflicts
            var errs = Ext.decode(data.tsrc_errors);
            var conflicts = errs.conflicts ? errs.conflicts : [];

            // first add the Source panel, for displaying the linked Source
            w.addModel('Source', data);

            // map each of the conflicts
            for (var i=0; i<conflicts.length; i++) {
                var c = conflicts[i];
                if (!w.panelMap[c.model]) {
                    w.addModel(c.model, data, c['with']);
                }
                w.addConflict(c.model, c.column, c.msg);
            }

            // if rendered, call doLayout
            if (w.rendered) w.doLayout();
        },
        addConflict: function(model, column, msg) {
            w.panelMap[model].addConflict(column, msg);
        },
        addModel: function(model, tsrcData, conflictWith) {
            if (map[model]) {
                w.panelMap[model] = w.get(0).add(map[model](tsrcData, model, conflictWith));
            }
            else if (model.substr(0, 5) == 'Fact.') {
                w.panelMap[model] = w.get(0).add(AIR2.Import.Resolve.Fact(tsrcData, model));
            }
            else {
                Logger("ERROR!!! Unknown conflict model '"+model+"'!!!");
            }
        }
    });

    // show and return the window
    if (cfg.originEl) w.show(cfg.originEl);
    else w.show();
    return w;
}
